const path = require('path');
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const { syncGitRepos } = require('./gitSyncService');

function pullGitReposFromReq(repos, callback) {
    if (!repos || !Array.isArray(repos)) {
        return callback(new Error('Invalid git repos'));
    }

    syncGitRepos(repos, callback);
}

async function searchCode(keyword, gitRepos, callback) {
    if (!keyword) return callback(null, []);

    const results = [];
    let processed = 0;

    for (const repo of gitRepos) {
        repo.name = repo.remoteUrl.split('/').pop().replace(/\.git$/, '');
        const repoPath = path.join(__dirname, 'workspace', repo.name);
        const branch = repo.branch || 'master';
        
        try {
            const cmd = `git -C ${repoPath} grep -n ${keyword} ${branch} --`;
            const { stdout } = await execAsync(cmd);
            stdout.split('\n').forEach(line => {
                if (line.length == 0) return;

                // 正则匹配拆分line，拆分前三个冒号
                if (!line) return;

                // 正则匹配拆分line，拆分前三个冒号
                const match = line.match(/^([^:]+):([^:]+):([0-9]*):(.*)$/);
                if (match) {
                    results.push({
                        lineNumber: match[3],
                        codeLine: match[4],
                        fileName: path.relative(repoPath, match[2]),
                        projectName: repo.name,
                        projectUrl: repo.remoteUrl,
                        branch: branch
                    });
                }
            });
        } catch (err) {
            console.error(err);
        } finally {
            if (++processed === gitRepos.length) {
                // 按项目、文件进行二级分组
                const groupedResults = {};
                results.forEach(item => {
                    if (!groupedResults[item.projectName]) {
                        groupedResults[item.projectName] = {
                            projectUrl: item.projectUrl,
                            branch: item.branch,
                            files: {}
                        };
                    }
                    const projectGroup = groupedResults[item.projectName];
                    if (!projectGroup.files[item.fileName]) {
                        projectGroup.files[item.fileName] = [];
                    }
                    projectGroup.files[item.fileName].push({
                        lineNumber: item.lineNumber,
                        codeLine: item.codeLine
                    });
                });
                callback(null, groupedResults);
            }
        }
    }
}

module.exports = {
    pullGitReposFromReq,
    searchCode
};